package cn.hlife.com.hlfhaemocyte.measure.view;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.charts.BarLineChartBase;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.ChartData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.LargeValueFormatter;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.greendaodemo.greendao.gen.DaoMaster;
import com.greendaodemo.greendao.gen.DaoSession;
import com.greendaodemo.greendao.gen.MeasureEntityDao;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.hlife.com.bluetooth20_connect.lib.BluetoothService;
import cn.hlife.com.hlfhaemocyte.R;
import cn.hlife.com.hlfhaemocyte.bean.MeasureEntity;
import cn.hlife.com.hlfhaemocyte.bluetooth.BluetoothPrint;
import cn.hlife.com.hlfhaemocyte.utils.LogUtils;
import cn.hlife.com.hlfhaemocyte.utils.SharedPreferencesUtils;
import cn.hlife.com.hlfhaemocyte.view.LoadingDialog;

public class MeasureRecordDetailsActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.WBC_result)
    TextView WBCResult;

    @BindView(R.id.wbc_tv)
    TextView wbcTv;
    @BindView(R.id.lym_tv)
    TextView lymTv;
    @BindView(R.id.mon_tv)
    TextView monTv;
    @BindView(R.id.gra_tv)
    TextView graTv;
    @BindView(R.id.lymp_tv)
    TextView lympTv;
    @BindView(R.id.monp_tv)
    TextView monpTv;
    @BindView(R.id.grap_tv)
    TextView grapTv;
    @BindView(R.id.hgb_tv)
    TextView hgbTv;
    @BindView(R.id.mch_tv)
    TextView mchTv;
    @BindView(R.id.plt_tv)
    TextView pltTv;
    @BindView(R.id.mchc_tv)
    TextView mchcTv;
    @BindView(R.id.rbc_tv)
    TextView rbcTv;
    @BindView(R.id.mcv_tv)
    TextView mcvTv;
    @BindView(R.id.hct_tv)
    TextView hctTv;
    @BindView(R.id.plty_tv)
    TextView pltyTv;
    @BindView(R.id.mpv_tv)
    TextView mpvTv;
    @BindView(R.id.RDWSD_tv)
    TextView RDWSDTv;
    @BindView(R.id.RDWCV_tv)
    TextView RDWCVTv;
    @BindView(R.id.pdw_tv)
    TextView pdwTv;
    @BindView(R.id.P_LCR_tv)
    TextView PLCRTv;
    @BindView(R.id.RDWCV_result)
    TextView RDWCV_result;
    @BindView(R.id.PDW_result)
    TextView PDW_result;
    @BindView(R.id.RDWSD_result)
    TextView RDWSD_result;
    @BindView(R.id.PLCR_result)
    TextView PLCR_result;
    private DaoSession daoSession;
    private TextView WBC, RGB, PLT, WBC_result, LYM_result, MON_result, GRA_result, LYMp_result, MONp_result, GRAp_result,
            HGB_result, MCH_result, MCHC_result, RBC_result, MCV_result, HCT_result, PLT_result, MPV_result, PCT_result;
    private LinearLayout print_Button;
    private ImageView returnImage;
    private DecimalFormat decimalFormat = new DecimalFormat("0.0");
    MeasureEntity measureEntity = null;
    LineChart RBC_chart, WBC_chart, PLT_chart;

    private LoadingDialog measureLoadingDialog, printBluetoothDialog;
    LinearLayout charGroup;
    Typeface mTf;
    boolean isEdit;
    EditText verifyPerson, inspector;
    String pltStringData, wbcStringData, rbcStringData;
    String jsonData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure_record);
        ButterKnife.bind(this);
        returnImage = (ImageView) findViewById(R.id.return_image);
        WBC_result = (TextView) findViewById(R.id.WBC_result);
        LYM_result = (TextView) findViewById(R.id.LYM_result);
        MON_result = (TextView) findViewById(R.id.MON_result);
        GRA_result = (TextView) findViewById(R.id.GRA_result);
        LYMp_result = (TextView) findViewById(R.id.LYMp_result);
        MONp_result = (TextView) findViewById(R.id.MONp_result);
        GRAp_result = (TextView) findViewById(R.id.GRAp_result);
        HGB_result = (TextView) findViewById(R.id.HGB_result);
        MCH_result = (TextView) findViewById(R.id.MCH_result);
        MCHC_result = (TextView) findViewById(R.id.MCHC_result);
        RBC_result = (TextView) findViewById(R.id.RBC_result);
        MCV_result = (TextView) findViewById(R.id.MCV_result);
        HCT_result = (TextView) findViewById(R.id.HCT_result);
        PLT_result = (TextView) findViewById(R.id.PLT_result);
        MPV_result = (TextView) findViewById(R.id.MPV_result);
//        TempFY_result = (TextView) findViewById(R.id.TempFY_result);
        PCT_result = (TextView) findViewById(R.id.PCT_result);
        print_Button = (LinearLayout) findViewById(R.id.print);
        charGroup = (LinearLayout) findViewById(R.id.char_group);
        RBC_chart = (LineChart) findViewById(R.id.RBC_chart);
        WBC_chart = (LineChart) findViewById(R.id.WBC_chart);
        PLT_chart = (LineChart) findViewById(R.id.PLT_chart);
        verifyPerson = (EditText) findViewById(R.id.verifyPerson);
        inspector = (EditText) findViewById(R.id.inspector);
        RGB = (TextView) findViewById(R.id.RGB);
        WBC = (TextView) findViewById(R.id.WBC);
        PLT = (TextView) findViewById(R.id.PLT);
        mTf = Typeface.createFromAsset(getAssets(), "fonts/苹果iOS9苹方纤细体UltraLight_50868_S60SC_C.ttf");
        setup(RBC_chart, "R");
        setup(WBC_chart, "W");
        setup(PLT_chart, "P");
        PLT.setTypeface(mTf);
        WBC.setTypeface(mTf);
        RGB.setTypeface(mTf);
        print_Button.setOnClickListener(this);
        returnImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MeasureRecordDetailsActivity.this.finish();
            }
        });
        Intent intent = getIntent();
        long id = intent.getLongExtra("_id", 0);
        isEdit = intent.getBooleanExtra("isEdit", false);
        //创建dbmanager类初始化数据库
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this.getApplicationContext(), "user.db", null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        daoSession = daoMaster.newSession();
        MeasureEntityDao measureEntityDao = daoSession.getMeasureEntityDao();
        if (id != 0) {
            measureEntity = measureEntityDao.queryBuilder()
                    .where(MeasureEntityDao.Properties.Id.eq(id)).unique();
        }
        setWidgetData(measureEntity);


        if (!isEdit) {
            inspector.setEnabled(false);
            verifyPerson.setEnabled(false);
        }
        pltStringData = measureEntity.getPLTNumberSum();
        wbcStringData = measureEntity.getWBCNumberSum();
        rbcStringData = measureEntity.getRBCNumberSum();
        jsonData = SharedPreferencesUtils.getInstance().getChartParameter(this);
        initView();

    }
    public  void  initView(){
        String  jsonStr= SharedPreferencesUtils.getInstance().getReportRefernce(this);
        if(!TextUtils.isEmpty(jsonStr)){
            JSONObject  jsonObject = null;
            try {
                jsonObject = new JSONObject(jsonStr);
                wbcTv.setText(jsonObject.getString("WBC"));
                lymTv.setText(jsonObject.getString("LYM"));
                monTv.setText(jsonObject.getString("MON"));
                graTv.setText(jsonObject.getString("GRA"));
                lympTv.setText(jsonObject.getString("LYMP"));
                monpTv.setText(jsonObject.getString("MONP"));
                grapTv.setText(jsonObject.getString("GRAP"));
                hgbTv.setText(jsonObject.getString("HGB"));
                mchTv.setText(jsonObject.getString("MCH"));
                mchcTv.setText(jsonObject.getString("MCHC"));
                rbcTv.setText(jsonObject.getString("RBC"));
                hctTv.setText(jsonObject.getString("HCT"));
                pltTv.setText(jsonObject.getString("PLT"));
                mcvTv.setText(jsonObject.getString("MCV"));
                pltyTv.setText(jsonObject.getString("PLTY"));
                mpvTv.setText(jsonObject.getString("MPV"));
                RDWSDTv.setText(jsonObject.getString("RDWSD"));
                RDWCVTv.setText(jsonObject.getString("RDWCV"));
                pdwTv.setText(jsonObject.getString("PDW"));
                PLCRTv.setText(jsonObject.getString("PLCR"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        setData(RBC_chart, rbcStringData, "RN");
        setData(WBC_chart, wbcStringData, "WN");
        setData(PLT_chart, pltStringData, "PN");
    }

    protected void setup(LineChart chart, String tag) {
        chart.getAxisLeft().setAxisMinimum(0f);
        chart.getAxisLeft().setDrawGridLines(false);
        chart.getXAxis().setDrawGridLines(false);
        if (tag.equals("R")) {
            chart.getAxisLeft().setAxisMaximum(1000);
        } else if (tag.equals("W")) {
            chart.getAxisLeft().setAxisMaximum(500);
        } else if (tag.equals("P")) {
            chart.getAxisLeft().setAxisMaximum(3000);
        }
        chart.getXAxis().setAxisMaximum(100);
        chart.getXAxis().setAxisMinimum(0);
        chart.getLegend().setEnabled(false);
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(false);
        if (chart instanceof BarLineChartBase) {

            BarLineChartBase mChart = (BarLineChartBase) chart;
            mChart.setDrawGridBackground(false);
            mChart.setDragEnabled(true);
            mChart.setScaleEnabled(true);
            mChart.setPinchZoom(false);

            YAxis leftAxis = mChart.getAxisLeft();
            leftAxis.removeAllLimitLines();
            leftAxis.setTypeface(mTf);
            leftAxis.setTextSize(10f);
            leftAxis.setDrawLabels(false);
            leftAxis.setTextColor(Color.DKGRAY);
            leftAxis.setValueFormatter(new LargeValueFormatter());

            XAxis xAxis = mChart.getXAxis();
            xAxis.setTypeface(mTf);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setTextSize(6f);
            xAxis.setDrawLabels(false);
            xAxis.setTextColor(Color.DKGRAY);

            mChart.getAxisRight().setEnabled(false);
        }
    }

    private void setData(LineChart mChart, String stringData, String tag) {
        String temp;
        temp = stringData.replace("[", "");
        temp = temp.replace("]", "");
        String[] strArray = temp.split(",");
        ArrayList<Entry> array = new ArrayList<Entry>();
        //TODO 需要修改
        String  jsonStr=SharedPreferencesUtils.getInstance().getMode(this);
        float xishu=1;
        if(!TextUtils.isEmpty(jsonStr)){
            try {

                if("QUANXYE".equals(jsonStr)){

                }else if("YUXISHI".equals(jsonStr)){
                    String  jsonS= SharedPreferencesUtils.getInstance().getYXSRefernce(this);
                    JSONObject  jsonObject=new JSONObject(jsonS);
                    String valueStr=null;
                    if("RN".equals(tag)){
                        valueStr=jsonObject.getString("RBC");
                    }else if("WN".equals(tag)){
                        valueStr=jsonObject.getString("WBC");
                    } else  if("PN".equals(tag)){
                        valueStr=jsonObject.getString("PLT");
                    }
                    xishu= Float.valueOf(valueStr);

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        try {
            JSONObject jsonO = new JSONObject(jsonData);
            float sumNumber = 0;
            for (int i = 0; i < strArray.length; i++) {

                sumNumber += Float.valueOf(strArray[i]);
                if (i % 5 == 0) {
                    String strTemp = jsonO.getString(tag + (array.size() + 1));
                    float tempInt;
                    if (TextUtils.isEmpty(strTemp)) {
                        tempInt = 1;
                    } else {
                        tempInt = Float.valueOf(strTemp);
                    }
                    array.add(new Entry(i, sumNumber * tempInt*xishu));
                    sumNumber = 0;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        LineDataSet set = new LineDataSet(array, "");
        set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
        set.setLabel(null);
        set.setDrawCircleHole(false);
        set.setColor(Color.DKGRAY);
        set.setLineWidth(1.8f);
        set.setCircleRadius(1.8f);
        set.setDrawCircles(false);//是否绘制 点
        set.setDrawValues(false);
        LineData data = new LineData(set);
        styleData(data);
        mChart.setData(data);
        mChart.animateY(1400, Easing.EasingOption.EaseInOutQuart);
    }

    protected void styleData(ChartData data) {
        Typeface mTf = Typeface.createFromAsset(getAssets(), "fonts/OpenSans-Regular.ttf");
        data.setValueTypeface(mTf);
        data.setValueTextSize(8f);
        data.setValueTextColor(Color.DKGRAY);
        data.setValueFormatter(new PercentFormatter());
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isEdit) {
            measureEntity.setInspector(inspector.getText().toString());
            measureEntity.setVerifyPerson(verifyPerson.getText().toString());
            MeasureEntityDao measureDao = daoSession.getMeasureEntityDao();
            measureDao.update(measureEntity);
        }

    }


    private void setWidgetData(MeasureEntity measureEntity) {
        if (measureEntity != null) {
            String WBC_result_str;
            double WBC_result_int = measureEntity.getWBCNUmber();
            if (WBC_result_int < 0) {
                WBC_result_str = "0";
            } else {
                WBC_result_str = decimalFormat.format(WBC_result_int);
            }
            WBC_result.setText(WBC_result_str);
            String LYM_result_str;
            double LYM_result_int = measureEntity.getLymNumber_Value();
            if (LYM_result_int < 0) {
                LYM_result_str = "0";
            } else {
                LYM_result_str = decimalFormat.format(LYM_result_int);
            }
            LYM_result.setText(LYM_result_str);

            String MON_result_str;
            double MON_result_int = measureEntity.getMidNumber_Value();
            if (MON_result_int < 0) {
                MON_result_str = "0";
            } else {
                MON_result_str = decimalFormat.format(MON_result_int);
            }
            MON_result.setText(MON_result_str);


            String GRA_result_str;
            double GRA_result_int = measureEntity.getNeuNumber_Value();
            if (GRA_result_int < 0) {
                GRA_result_str = "0";
            } else {
                GRA_result_str = decimalFormat.format(GRA_result_int);
            }
            GRA_result.setText(GRA_result_str);

            String LYMp_result_str;
            double LYMp_result_int = measureEntity.getLymPercent_Value();
            if (LYMp_result_int < 0) {
                LYMp_result_str = "0";
            } else {
                LYMp_result_str = decimalFormat.format(LYMp_result_int);
            }

            LYMp_result.setText(LYMp_result_str);

            String MONp_result_str;
            double MONp_result_int = measureEntity.getMidPercent_Value();
            if (MONp_result_int < 0) {
                MONp_result_str = "0";
            } else {
                MONp_result_str = decimalFormat.format(MONp_result_int);
            }

            MONp_result.setText(MONp_result_str);


            String GRAp_result_str;
            double GRAp_result_int = measureEntity.getNeuPercent_Value();
            if (GRAp_result_int < 0) {
                GRAp_result_str = "0";
            } else {
                GRAp_result_str = decimalFormat.format(GRAp_result_int);
            }
            GRAp_result.setText(GRAp_result_str);


            String HGB_result_str;
            double HGB_result_int = measureEntity.getHGB_Value();
            if (HGB_result_int < 0) {
                HGB_result_str = "0";
            } else {
                HGB_result_str = decimalFormat.format(HGB_result_int);
            }
            HGB_result.setText(HGB_result_str);

            String MCH_result_str;
            double MCH_result_int = measureEntity.getMCH_Value();
            if (MCH_result_int < 0) {
                MCH_result_str = "0";
            } else {
                MCH_result_str = decimalFormat.format(MCH_result_int);
            }

            MCH_result.setText(MCH_result_str);


            String MCHC_result_str;
            double MCHC_result_int = measureEntity.getMCHC_Value();
            if (MCHC_result_int < 0) {
                MCHC_result_str = "0";
            } else {
                MCHC_result_str = decimalFormat.format(MCHC_result_int);
            }

            MCHC_result.setText(MCHC_result_str);
            String MCV_result_str;
            double MCV_result_int = measureEntity.getMCV_Value();
            if (MCV_result_int < 0) {
                MCV_result_str = "0";
            } else {
                MCV_result_str = decimalFormat.format(MCV_result_int);
            }

            MCV_result.setText(MCV_result_str);


            String PLT_result_str;
            double PLT_result_int = measureEntity.getPLTNumber();
            if (PLT_result_int < 0) {
                PLT_result_str = "0";
            } else {
                PLT_result_str = decimalFormat.format(PLT_result_int);
            }

            PLT_result.setText(PLT_result_str);

            String MPV_result_str;
            double MPV_result_int = measureEntity.getMPV_Value();
            if (PLT_result_int < 0) {
                MPV_result_str = "0";
            } else {
                MPV_result_str = decimalFormat.format(MPV_result_int);
            }
            MPV_result.setText(MPV_result_str);

            String RBC_result_str;
            double RBC_result_int = measureEntity.getRBCNumber();
            if (RBC_result_int < 0) {
                RBC_result_str = "0";
            } else {
                RBC_result_str = decimalFormat.format(RBC_result_int);
            }
            RBC_result.setText(RBC_result_str);

            String HCT_result_str;
            double HCT_result_int = measureEntity.getHCT_Value();
            if (HCT_result_int < 0) {
                HCT_result_str = "0";
            } else {
                HCT_result_str = decimalFormat.format(HCT_result_int);
            }

            HCT_result.setText(HCT_result_str);
            String PCT_result_str;
            double PCT_result_int = measureEntity.getPCT_Value();
            if (PCT_result_int < 0) {
                PCT_result_str = "0";
            } else {
                PCT_result_str = decimalFormat.format(PCT_result_int);
            }
            PCT_result.setText(PCT_result_str);


            String RDWCV_result_str;
            double RDWCV_result_int = measureEntity.getRDWCV_Value();
            if (RDWCV_result_int < 0) {
                RDWCV_result_str = "0";
            } else {
                RDWCV_result_str = decimalFormat.format(RDWCV_result_int);
            }
            RDWCV_result.setText(RDWCV_result_str);


            String RDWSD_result_str;
            double RDWSD_result_int = measureEntity.getRDWSD_Value();
            if (RDWSD_result_int < 0) {
                RDWSD_result_str = "0";
            } else {
                RDWSD_result_str = decimalFormat.format(RDWSD_result_int);
            }
            RDWSD_result.setText(RDWSD_result_str);

            String PDW_result_str;
            double PDW_result_int = measureEntity.getPDW_Value();
            if (PDW_result_int < 0) {
                PDW_result_str = "0";
            } else {
                PDW_result_str = decimalFormat.format(PDW_result_int);
            }
            PDW_result.setText(PDW_result_str);
            String PLCR_result_str;
            double PLCR_result_int = measureEntity.getPLCR_Value();
            if (PLCR_result_int < 0) {
                PLCR_result_str = "0";
            } else {
                PLCR_result_str = decimalFormat.format(PLCR_result_int);
            }
            PLCR_result.setText(PLCR_result_str);
//            TempFY_result.setText(measureEntity.getTempFY() + "");
            inspector.setText(measureEntity.getInspector());
            verifyPerson.setText(measureEntity.getVerifyPerson());
        }
    }

    @Override
    public void onClick(View v) {
        int viewID = v.getId();
        switch (viewID) {
            case R.id.print:

                final BluetoothService bluetoothService = BluetoothPrint.getInstance().getBluetoothService();
                if (bluetoothService != null) {
                    if (bluetoothService.getState() == BluetoothService.STATE_CONNECTED) {
                          Toast.makeText(this, "开始打印", Toast.LENGTH_SHORT).show();
                        print_Button.setEnabled(false);
                        print_Button.setBackgroundResource(R.drawable.print_pressed_shape);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Bitmap bitmap = BluetoothPrint.getInstance().createReportBitmap(measureEntity);
                                    try {
                                        BluetoothPrint.getInstance().PrintBitmap(bitmap);
                                        bitmap = getViewBitmap(charGroup);
                                        BluetoothPrint.getInstance().PrintBitmap(bitmap);
                                        bluetoothService.write("\n\n\n\n".getBytes());
                                        if(MCH_result!=null){
                                            LogUtils.e("MCH_result!=null");
                                            MCH_result.post(new Runnable() {
                                                @Override
                                                public void run() {
                                                    print_Button.setEnabled(true);
                                                    print_Button.setBackgroundResource(R.drawable.print_normal_shape);
                                                }
                                            });
                                        }else {
                                            LogUtils.e("MCH_result==null");

                                        }
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();

                    } else {
                        Toast.makeText(this, "打印机未连接", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

    private Bitmap getViewBitmap(View v) {
        v.clearFocus();
        v.setPressed(false);
        boolean willNotCache = v.willNotCacheDrawing();
        v.setWillNotCacheDrawing(false);
        int color = v.getDrawingCacheBackgroundColor();
        v.setDrawingCacheBackgroundColor(Color.WHITE);

        if (color != 0) {
            v.destroyDrawingCache();
        }
        v.buildDrawingCache();
        Bitmap cacheBitmap = v.getDrawingCache();
        if (cacheBitmap == null) {
            return null;
        }
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
        v.destroyDrawingCache();
        v.setWillNotCacheDrawing(willNotCache);
        v.setDrawingCacheBackgroundColor(color);
        Matrix matrix = new Matrix();
        matrix.postScale(0.8f, 0.8f);
        matrix.postRotate(90);
        Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return bm;
    }
}
